package com.monitor.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.monitor.entity.ErpClients;
import com.monitor.entity.ErpClientsMateriel;
import com.monitor.entity.ErpCustomer;
import com.monitor.entity.ErpManagement;
import com.monitor.entity.ErpSystemMessage;
import com.monitor.service.*;
import com.monitor.util.DataUtil;
import com.monitor.util.IDUtils;
import com.monitor.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 采购订单表 前端控制器
 * </p>
 *
 * @author LX
 * @since 2018-09-09
 */
@RestController
@RequestMapping("/erpClients")
@Api(description="采购订单")
public class ErpClientsController {
    @Resource
    private ErpCustomerService erpCustomerService;

    @Resource
    private ErpClientsService clientsService;
    @Resource
    private ErpClientsMaterielService materielService;
    @Resource
    private ErpCustomerService customerService;
    @Resource
    private ErpSystemMessageService messageService;

    @Resource
    private ErpInvoiceService erpInvoiceService;
    
    @Resource
    private ErpManagementService erpManagementService;
    
    @RequestMapping("/inertOrUpdateClients")
    @ApiOperation("添加Or修改采购订单表")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query")*/
    })
    public @ResponseBody Result<ErpClients> inertOrUpdateCustFinanceVice(String json) {
        //ErpClients customerCar,
        //        List<ErpClientsMateriel> materiels
//        JSONObject jsonObject=JSONObject.fromObject(objectStr);
//        Student stu=(ErpClients)JSONObject.toBean(jsonObject, ErpClients.class);
        Result<ErpClients> result=new Result<ErpClients>();

        ErpClients  customerCar = JSON.parseObject(json, ErpClients.class);
        List<ErpClientsMateriel> materiels = customerCar.getMateriels();

        try{
            customerCar.setWorkDt(DataUtil.getStringDate());
            if(customerCar.getShenpi()!=null&&customerCar.getShenpi()!=""){

            }else{
                customerCar.setShenpi("未审批");
            }
            //查到订单最后一个并截取字符串然后五位然后在添加的时候+1

            //clientsService.insertOrUpdate(customerCar);

            String time=DataUtil.dateToStr(new Date());
            String shi=DataUtil.getStringDate(time);
            String id="CGDD"+shi;
            List<ErpClients> erpMaterielFlows = clientsService.selectList(new EntityWrapper<ErpClients>().like("sheet_id", id).orderBy("id", false));
            if(erpMaterielFlows.size()>0) {
            	ErpClients client=erpMaterielFlows.get(0);
            	String str=client.getSheetId().substring(12, client.getSheetId().length());
         		str=IDUtils.addOne(str);
         		id+=str;
            }else {
            	id+="00001";
            }
            customerCar.setSheetId(id);
            if(customerCar.getAllManager()!=null&&!customerCar.getAllManager().equals("")){ //判断是否是总经理 审核 如果是总经理就修改为已审核
            	List<ErpSystemMessage> msgList=messageService.selectList(new EntityWrapper<ErpSystemMessage>().eq("send_content", customerCar.getSheetId()));
            	if(msgList!=null) {
            		for(ErpSystemMessage msg:msgList) {
            			msg.setSendFlag("已读");
            			messageService.updateById(msg);
            		}
            	}
            }else {
            	 customerCar.setShenpi("待审批");
                 //采购订单生成消息
                 ErpSystemMessage message=new ErpSystemMessage();
                 ErpCustomer customer=customerService.selectById(customerCar.getCustomerId());
                 ErpCustomer customer1=customerService.selectOne(new EntityWrapper<ErpCustomer>().eq("cus_name",customerCar.getCustomerName()));
                 message.setCreateDt(new Date());
                 message.setSendUserId(0);
                 message.setSendCustId(customerCar.getCustomerId());
                 message.setSendUserName(customer.getCusName());
                 message.setReceiveUserId(0);
                 message.setReceiveCustId(customer1.getId());
                 message.setSendFlag("未读");
                 message.setMessageType("采购订单");
                 message.setCompanys(customer1.getCusName());
                 message.setSendContent(customerCar.getSheetId());
                 messageService.insert(message);
            	
            }
            clientsService.insertOrUpdate(customerCar);

            for (ErpClientsMateriel m:materiels) {
                m.setClientsId(customerCar.getId());
                //m.setInvoiceType(customerCar.getInvoiceType());
                materielService.insertOrUpdate(m);
            }


            result.setCount(1);
            result.setData(customerCar);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }


    @RequestMapping("/getClientsById")
    @ApiOperation("根据采购订单id查看采购订单信息")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "clientsId", value = "采购订单ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<ErpClients> getClientsById(Integer clientsId) {
        Result<ErpClients> result=new Result<ErpClients>();
        try{
            ErpClients erpClients=clientsService.selectById(clientsId);
            erpClients.setMateriels(materielService.selectList(new EntityWrapper<ErpClientsMateriel>().eq("clients_id",clientsId)));
            result.setCount(1);
            result.setData(erpClients);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }
    @RequestMapping("/removeClientsById")
    @ApiOperation("根据采购订单id删除采购订单")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "id", value = "采购订单ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<Integer> removeClientsById(Integer id) {
        Result<Integer> result=new Result<Integer>();
        try{
            result.setCount(1);
            result.setData(materielService.deleteById(id)?1:0);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }
    @RequestMapping("/getClientsAll")
    @ApiOperation("根据采购订单id查看采购订单信息汇总")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),*/
//            @ApiImplicitParam(name = "clientsId", value = "采购订单ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<List<ErpClients>> getClientsAll(String startDate  ,String endDate) {
        Result<List<ErpClients>>  result=new Result<List<ErpClients>> ();
        try{
        	List<ErpClients> erpClients =new ArrayList<>();
        	if(startDate!=null&&!startDate.equals("")) {
        		erpClients = clientsService.selectList(new EntityWrapper<ErpClients>().between("workDt",startDate,endDate));
        	}else {
        		erpClients = clientsService.selectList(new EntityWrapper<ErpClients>());
        	}
//            erpClients.setMateriels(materielService.selectList(new EntityWrapper<ErpClientsMateriel>().eq("clients_id",clientsId)));
            result.setCount(1);
            result.setData(erpClients);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }


    @RequestMapping("/updateClientsById")
    @ApiOperation("根据采购订单id修改采购订单状态")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "clientsId", value = "采购订单ID", required = false, dataType = "int", paramType = "query")*/
    })
    public @ResponseBody
    Result<Integer> updateClientsById(ErpClients customerCar) {
        Result<Integer> result=new Result<Integer>();
        try{
            result.setCount(1);
            result.setData(clientsService.updateById(customerCar)?1:0);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }

    @RequestMapping("/getClientsBycustId")
    @ApiOperation("根据采购订单id查看采购订单信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<List<ErpClients>> getClientsBycustId(Integer custId,String startTime,String endTime) {
        Result<List<ErpClients>> result=new Result<List<ErpClients>>();
        try{
            result.setCount(1);
            result.setData(clientsService.selectList(new EntityWrapper<ErpClients>().eq("customer_id",custId).and().ge("work_dt",startTime).and().le("work_dt",endTime)));
        }catch (Exception e){e.printStackTrace();}
        return result;
    }
    @RequestMapping("/getClientsPageBycustId_lxl")
    @ApiOperation("根据客户ID查询采购订单分页")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<List<ErpClients>> getClientsPageBycustId_lxl( Integer custId) {
        Result<List<ErpClients>> result=new Result<>();
        try{

//            Page<ErpClients> page1=new Page<ErpClients>(page,limit);

            //查询旗下所有用户的
//            String custIdsStd=customerService.getcustOfMe(custId);
//            String aa=custId+","+custIdsStd;
//            List<ErpClients> carPage=clientsService.selectList(new EntityWrapper<ErpClients>().in("customer_id",aa));
            List<ErpClients> carPage=clientsService.selectList(new EntityWrapper<ErpClients>().eq("customer_id",custId));
            carPage.parallelStream().forEach(car->{
                ErpClientsMateriel erpClientsMateriel = materielService.selectOne(new EntityWrapper<ErpClientsMateriel>().eq("clients_id", car.getId()));
                if (erpClientsMateriel!=null){
                car.setMessage(" "+erpClientsMateriel.getMaterielName()+" "+erpClientsMateriel.getMaterielBrand()+" "+erpClientsMateriel.getMaterielSpecifications()+" "+erpClientsMateriel.getMaterielModel()+" "+erpClientsMateriel.getMaterielPlace()+" "+erpClientsMateriel.getOutAmount()+" "+erpClientsMateriel.getMaterielUnit()+"  已入库"+erpClientsMateriel.getMaterielAmount()+erpClientsMateriel.getMaterielUnit());
                car.setMateriels(materielService.selectList(new EntityWrapper<ErpClientsMateriel>().eq("clients_id",car.getId())));
                }
            });

            //Page<ErpCustomerCar> page=new Page<ErpCustomerCar>(1,2);
            result.setCount(carPage.size());
            result.setData(carPage);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }


    @RequestMapping("/getClientsPageBycustId")
    @ApiOperation("根据客户ID查询采购列表分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = false, dataType = "String", paramType = "query")
    })
    public @ResponseBody
    Result<List<ErpClients>> getClientsPageBycustId(Integer custId,String startTime,String endTime) {
        Result<List<ErpClients>> result=new Result<>();
        try{
            EntityWrapper<ErpClients>  erpClientsList= new EntityWrapper<ErpClients>();
            if(startTime!=null&&!startTime.equals("")&endTime!=null&&!endTime.equals("")){
                erpClientsList.and().ge("work_dt",startTime).and().le("work_dt",endTime);
            }
            List<ErpClients> carPage=clientsService.selectList(erpClientsList.eq("customer_id",custId).orderBy("work_dt", false));
            carPage.parallelStream().forEach(car->{
                List<ErpClientsMateriel> erpClientsMateriel = materielService.selectList(new EntityWrapper<ErpClientsMateriel>().eq("clients_id",car.getId()));
                if (erpClientsMateriel!=null){
                	String message="";
                	for(ErpClientsMateriel mater:erpClientsMateriel) {
                		message=message+" "+mater.getMaterielName()+" "+mater.getMaterielBrand()+" "+mater.getMaterielSpecifications()+" "+mater.getMaterielModel()+" "+mater.getMaterielPlace()+" "+mater.getMaterielAmount()+" "+mater.getMaterielUnit()+"  已入库"+mater.getOutAmount()+mater.getMaterielUnit();
                	}
                	car.setMessage(message);
                    car.setMateriels(erpClientsMateriel);
                }
            });
            result.setCount(carPage.size());
            result.setData(carPage);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }



    @RequestMapping("/getClientsById_lxl")
    @ApiOperation("查询采购订单单条信息 by id")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "customerCode", value = "客户编号", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "erp_clients_id", value = "采购订单id", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<List<ErpClients>> getClientsById_lxl(Integer erp_clients_id) {
        Result<List<ErpClients>> result=new Result<>();
        try{
            //查询单个id信息的订单
            List<ErpClients> carPage=clientsService.selectList(new EntityWrapper<ErpClients>().eq("id",erp_clients_id));
            result.setCount(carPage.size());
            result.setData(carPage);
        }catch (Exception e){e.printStackTrace();}
        return result;
    }

    @RequestMapping("/selectBySheelId")
    public Result<Map<String, Object>> selectBySheelId(String sheelId){
    	Map<String, Object> map=new HashMap<>();
    	ErpClients client=clientsService.selectOne(new EntityWrapper<ErpClients>().eq("sheet_id", sheelId));
    	if(client!=null) {
    		map.put("client", client);
    		List<ErpClientsMateriel> list=materielService.selectList(new EntityWrapper<ErpClientsMateriel>().eq("clients_id", client.getId()));
    		map.put("clientMateriel", list);
    		return new Result<Map<String,Object>>(map, 1);
    	}else {
    		return new Result<Map<String,Object>>(null, 1);
    	}
    }

    @RequestMapping("/shenhe")
    @ApiOperation("采购列表订单号点击确定审核")
    @ApiImplicitParams({
           @ApiImplicitParam(name = "id", value = "采购订单id", required = false, dataType = "int", paramType = "query"),
           @ApiImplicitParam(name = "type", value = "审批者身份", required = false, dataType = "String", paramType = "query"),
           @ApiImplicitParam(name = "name", value = "审批者", required = false, dataType = "String", paramType = "query")
    })
    public Result<Boolean> shenhe(String type,int id,String name){
    	Boolean count=false;
    	ErpClients clients=clientsService.selectById(id);
    	if(type.trim().equals("部门经理")) {
    		if((clients.getGroupManager()==null||clients.getGroupManager().equals(""))&&clients.getShenpi().equals("未审批")) {
    			clients.setGroupManager(name);
    			count=clientsService.updateById(clients);
    		}
    	}else if(type.trim().equals("财务经理")) {
    		if((clients.getFinance()==null||clients.getFinance().equals(""))&&clients.getShenpi().equals("未审批")) {
    			clients.setFinance(name);
    			count=clientsService.updateById(clients);
    		}
    	}else if(type.trim().equals("超级用户")) {
    		//if((clients.getAllManager()==null||clients.getAllManager().equals(""))&&clients.getShenpi().equals("未审批")) {
    			clients.setAllManager(name);
    			clients.setShenpi("已审批");
    			count=clientsService.updateById(clients);
    		//}
            List<ErpSystemMessage> msgList=messageService.selectList(new EntityWrapper<ErpSystemMessage>().eq("send_content", clients.getSheetId()));
            if(msgList!=null) {
               for(ErpSystemMessage msg:msgList) {
                 msg.setSendFlag("已读");
                 messageService.updateById(msg);
               }
            }
    	}
    	return new Result<Boolean>(count, 1);
    }
    
    @RequestMapping("/deleteClients")
    @ApiOperation("采购列表订单号点击删除")
    @ApiImplicitParam(name = "id", value = "采购订单id", required = false, dataType = "int", paramType = "query")
    public Result<Boolean> deleteClients(int id){
    	try {
			ErpClients clients=clientsService.selectById(id);
			messageService.delete(new EntityWrapper<ErpSystemMessage>().eq("send_content", clients.getSheetId()));
			erpManagementService.delete(new EntityWrapper<ErpManagement>().eq("work_id", clients.getSheetId()));
			materielService.delete(new EntityWrapper<ErpClientsMateriel>().eq("clients_id", clients.getId()));
			Boolean count=clientsService.deleteById(id);
			return new Result<Boolean>(count, 1);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new Result<>(1, e.getMessage());
		}
    }
}

